package cn.tedu.mall.search.service.impl;

import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.pojo.product.model.Spu;
import cn.tedu.mall.pojo.search.entity.SpuForElastic;
import cn.tedu.mall.product.service.front.IForFrontSpuService;
import cn.tedu.mall.search.repository.SpuForElasticRepository;
import cn.tedu.mall.search.service.ISearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author BJ
 * @date 2022/11/5 14:02
 */
@Service
@Slf4j
public class SpuForElasticRepositoryImpl implements ISearchService {
    // dubbo 调用Product模块分页查询所有spu
    @DubboReference
    private IForFrontSpuService spuService;
    @Autowired
    private SpuForElasticRepository elasticRepository;

    @Override
    public JsonPage<SpuForElastic> search(String keyword, Integer page, Integer pageSize) {
        // 根据关键字在ES中搜索spu商品(SpringData框架中 page是从0页开始的)
        Page<SpuForElastic> spuForElastics = elasticRepository.querySearch(keyword, PageRequest.of(page - 1, pageSize));
        // 将Page转换成JsonPage
        JsonPage<SpuForElastic> jsonPage = new JsonPage<>();
        jsonPage.setPage(page);
        jsonPage.setPageSize(pageSize);
        jsonPage.setTotalPage(spuForElastics.getTotalPages());
        jsonPage.setTotal(spuForElastics.getTotalElements());
        jsonPage.setList(spuForElastics.getContent());

        return jsonPage;
    }

    @Override
    public void loadSpuByPage() {
        // 将Product模块中分页查询出来的spu商品数据，赋值到SpuForElastic（ES实体类中）
        int i = 1; // 页码
        int pages; //总页数
        do {
            JsonPage<Spu> spus = spuService.getSpuByPage(i, 2);
            List<SpuForElastic> elastics = new ArrayList<>();
            // spus.getList() 包含所有分页信息
            for (Spu spu : spus.getList()) {
                SpuForElastic elastic = new SpuForElastic();
                BeanUtils.copyProperties(spu, elastic);
                elastics.add(elastic);
            }
            // 将分页信息保存到ES中
            elasticRepository.saveAll(elastics);
            i++;
            pages = spus.getTotalPage();
        } while (i < pages);
    }
}
